package org.glut.backend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.glut.backend.domain.Comment;
import org.glut.backend.mapper.CommentMapper;
import org.glut.backend.service.ICommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    // 原有方法保持不变...
    @Override
    public List<Comment> getCommentsByTargetId(Long targetId) {
        List<Comment> comments = baseMapper.selectByTargetId(targetId);
        return buildCommentTree(comments);
    }

    private List<Comment> buildCommentTree(List<Comment> comments) {
        List<Comment> result = new ArrayList<>();
        Map<Long, Comment> commentMap = new HashMap<>();

        for (Comment comment : comments) {
            Comment vo = new Comment();
            BeanUtils.copyProperties(comment, vo);
            vo.setChildren(new ArrayList<>());
            commentMap.put(vo.getId(), vo);
        }

        for (Comment comment : comments) {
            Comment vo = commentMap.get(comment.getId());
            if (comment.getParentId() == 0) {
                result.add(vo);
            } else {
                Comment parent = commentMap.get(comment.getParentId());
                if (parent != null) {
                    parent.getChildren().add(vo);
                }
            }
        }
        return result;
    }

    @Override
    public boolean addComment(Comment comment) {
        return save(comment);
    }

   /* // 新增：修改评论实现
    @Override
    public boolean updateComment(Comment comment) {
        // 仅更新内容和修改时间（假设Comment有updateTime字段）
        Comment existing = getById(comment.getId());
        if (existing == null) {
            return false;
        }
        // 验证权限（确保是评论作者）
        if (!existing.getUserId().equals(comment.getUserId())) {
            return false;
        }
        existing.setContent(comment.getContent());
        return updateById(existing);
    }*/

    // 新增：删除评论实现
    @Override
    public boolean deleteComment(Long id) {
        // 实际应用中应先验证权限（查询userId并与当前登录用户比对）
        return removeById(id);
    }
}